'use strict';
const db = uniCloud.database();
const dbCmd = db.command;

/**
 * 记录积分变化（内联版本）
 * 注意：此函数应该在积分已经更新之后调用
 * balance_after 会自动查询当前最新的积分余额
 */
async function logPointChange({ userId, changeAmount, changeType, description, relatedOrderId = null }) {
  try {
    // 查询用户当前积分（此时积分已经更新过了）
    const userRes = await db.collection('users').doc(userId).field({ points: 1 }).get();
    if (!userRes.data || userRes.data.length === 0) {
      console.error(`[积分记录] 用户不存在: ${userId}`);
      return;
    }
    const currentPoints = userRes.data[0].points || 0;
    // balance_after 就是当前积分（因为积分已经更新过了）
    const balanceAfter = currentPoints;

    await db.collection('point_records').add({
      user_id: userId,
      change_amount: changeAmount,
      change_type: changeType,
      description: description,
      related_order_id: relatedOrderId,
      balance_after: balanceAfter,
      create_time: Date.now()
    });
    console.log(`[积分记录] 用户 ${userId} 积分变化: ${changeAmount > 0 ? '+' : ''}${changeAmount}, 余额: ${balanceAfter}, 原因: ${description}`);
  } catch (error) {
    console.error(`[积分记录] 记录失败:`, error);
  }
}

/**
 * 订单状态检查定时任务
 * 每4小时执行一次，检查倒计时期间的订单是否被取消
 * 如果订单被取消，及时核减已发放的佣金和积分
 */
exports.main = async (event, context) => {
    console.log('开始执行订单状态检查定时任务...');
    const now = Date.now();
    
    // 查找所有倒计时大于0的订单（即订单完成后15天内的订单）
    // activation_countdown > 0 表示还在倒计时期间
    const ordersToCheck = await db.collection('orders').where({
        activation_countdown: dbCmd.gt(0),
        activation_date: dbCmd.gt(now) // 还未到激活日期
    }).get();

    if (ordersToCheck.data.length === 0) {
        console.log('没有需要检查的订单。任务结束。');
        return { checkedCount: 0, cancelledCount: 0 };
    }

    console.log(`发现 ${ordersToCheck.data.length} 条倒计时中的订单，开始检查状态...`);
    let checkedCount = 0;
    let cancelledCount = 0;
    let refundedCount = 0;

    // 获取access_token用于查询微信订单状态
    let accessToken;
    try {
        const tokenRes = await uniCloud.callFunction({
            name: 'wx-api-center',
            data: { action: 'getAccessToken' }
        });
        if (tokenRes.result.code !== 0) {
            throw new Error(tokenRes.result.message);
        }
        accessToken = tokenRes.result.accessToken;
        console.log('✅ access_token获取成功');
    } catch (err) {
        console.error('❌ 获取access_token失败:', err.message);
        return { error: '获取access_token失败', message: err.message };
    }

    for (const order of ordersToCheck.data) {
        checkedCount++;
        const orderId = order._id;
        
        try {
            // 调用微信API获取订单最新状态
            const detailUrl = `https://api.weixin.qq.com/channels/ec/order/get?access_token=${accessToken}`;
            const detailRes = await uniCloud.httpclient.request(detailUrl, {
                method: 'POST',
                contentType: 'json',
                dataType: 'json',
                data: { order_id: orderId }
            });

            if (!detailRes.data || detailRes.data.errcode !== 0) {
                console.error(`❌ 获取订单 ${orderId} 详情失败:`, detailRes.data?.errmsg);
                continue;
            }

            const wechatOrder = detailRes.data.order;
            const wechatStatus = wechatOrder.status;
            
            // 映射微信订单状态
            let newStatus = order.status;
            if (wechatStatus === 200) {
                newStatus = 'cancelled';
            } else if (wechatStatus === 250) {
                newStatus = 'refunded';
            }
            
            // 如果订单状态变为取消或退款，需要核减佣金和积分
            if ((newStatus === 'cancelled' || newStatus === 'refunded') && order.status === 'completed') {
                console.log(`⚠️ 订单 ${orderId} 状态变化: ${order.status} → ${newStatus}`);
                
                try {
                    // 核减购买用户积分
                    if (order.buyer_points_awarded > 0) {
                        await db.collection('users').doc(order.buyer_id).update({
                            points: dbCmd.inc(-order.buyer_points_awarded)
                        });
                        console.log(`✅ 已核减购买用户 ${order.buyer_id} 的积分 ${order.buyer_points_awarded}`);

                        // 记录积分变化
                        await logPointChange({
                            userId: order.buyer_id,
                            changeAmount: -order.buyer_points_awarded,
                            changeType: newStatus === 'cancelled' ? 'order_cancel' : 'order_refund',
                            description: `订单${newStatus === 'cancelled' ? '取消' : '退款'}核减（定时任务检测）`,
                            relatedOrderId: orderId
                        });
                    }

                    // 核减推广人积分
                    if (order.promoter_id && order.points_awarded > 0) {
                        await db.collection('users').doc(order.promoter_id).update({
                            points: dbCmd.inc(-order.points_awarded)
                        });
                        console.log(`✅ 已核减推荐人 ${order.promoter_id} 的积分 ${order.points_awarded}`);

                        // 记录积分变化
                        await logPointChange({
                            userId: order.promoter_id,
                            changeAmount: -order.points_awarded,
                            changeType: newStatus === 'cancelled' ? 'order_cancel' : 'order_refund',
                            description: `推广订单${newStatus === 'cancelled' ? '取消' : '退款'}核减（定时任务检测）`,
                            relatedOrderId: orderId
                        });
                    }
                    
                    // 核减佣金（根据佣金状态）
                    if (order.promoter_id && order.commission_amount > 0) {
                        if (order.commission_status === 'pending') {
                            // 待激活佣金
                            await db.collection('users').doc(order.promoter_id).update({
                                commission_pending: dbCmd.inc(-order.commission_amount)
                            });
                            console.log(`✅ 已核减推荐人 ${order.promoter_id} 的待激活佣金 ${order.commission_amount} 分`);
                        } else if (order.commission_status === 'activated') {
                            // 已激活佣金（可提现余额）
                            await db.collection('users').doc(order.promoter_id).update({
                                commission_available: dbCmd.inc(-order.commission_amount),
                                commission_total: dbCmd.inc(-order.commission_amount)
                            });
                            console.log(`✅ 已核减推荐人 ${order.promoter_id} 的可提现佣金 ${order.commission_amount} 分`);
                        }
                    }
                    
                    // 更新订单状态
                    await db.collection('orders').doc(orderId).update({
                        status: newStatus,
                        commission_status: 'cancelled',
                        last_sync_time: now
                    });
                    
                    if (newStatus === 'cancelled') {
                        cancelledCount++;
                    } else {
                        refundedCount++;
                    }
                    
                    console.log(`✅ 订单 ${orderId} 状态已更新为 ${newStatus}，佣金和积分已核减`);
                } catch (err) {
                    console.error(`❌ 处理订单 ${orderId} 取消逻辑失败:`, err.message);
                }
            } else if (newStatus !== order.status) {
                // 其他状态变化，只更新状态
                await db.collection('orders').doc(orderId).update({
                    status: newStatus,
                    last_sync_time: now
                });
                console.log(`✅ 订单 ${orderId} 状态已更新: ${order.status} → ${newStatus}`);
            }
            
        } catch (err) {
            console.error(`❌ 检查订单 ${orderId} 失败:`, err.message);
        }
    }

    console.log(`任务完成。检查了 ${checkedCount} 条订单，发现 ${cancelledCount} 条取消订单，${refundedCount} 条退款订单。`);
    return { 
        checkedCount, 
        cancelledCount, 
        refundedCount,
        message: `检查了 ${checkedCount} 条订单，发现 ${cancelledCount} 条取消订单，${refundedCount} 条退款订单`
    };
};

